<template>
  <div>
    <van-search
      v-model="value"
      shape="round"
      background="#007bff"
      placeholder="请输入搜索关键词"
      v-focus
      @input="inputFn"
      @search="searchSureFn"
    >
      <template #left>
        <van-icon
          name="arrow-left"
          color="white"
          size="0.48rem"
          class="goback"
          @click="$router.back()"
        />
      </template>
    </van-search>
    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="value.length > 0">
      <div
        class="sugg-item"
        v-for="(str, index) in searchSuggestionList"
        :key="index"
        v-html="lightKey(str)"
        @click="searchListFn(str)"
      ></div>
    </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span class="history-item" v-for="(str,index) in historyList" :key="index" @click="toSearchResult(str)">{{str}}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { searchSuggestion } from '@/api'
export default {
  data () {
    return {
      value: '',
      timer: null,
      searchSuggestionList: [],
      historyList: JSON.parse(localStorage.getItem('history')) || []
    }
  },
  methods: {
    // 输入框内容发生变化时触发
    inputFn () {
      // 防抖
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (this.value.length > 0) {
          const res = await searchSuggestion(this.value)
          if (res.data.data.options[0] === null) {
            this.searchSuggestionList = []
          } else {
            this.searchSuggestionList = res.data.data.options
          }
          // console.log(res)
        }
      }, 100)
    },
    // 确认搜索输入框内容时，触发
    searchSureFn () {
      this.historyList.push(this.value)
      this.historyList = [...new Set(this.historyList)]
      setTimeout(() => {
        this.$router.push('/search/' + this.value)
      }, 0)
    },
    // 关键字高亮设置
    lightKey (str) {
      if (str) {
        const res = new RegExp(this.value, 'ig')
        return str.replace(res, (val) => {
          return `<span style="color:red">${val}</span>`
        })
      } else {
        this.searchSuggestionList = []
      }
    },
    // 点击联想内容项时，触发
    searchListFn (str) {
      this.historyList.push(str)
      this.historyList = [...new Set(this.historyList)]
      setTimeout(() => {
        this.$router.push('/search/' + str)
      }, 0)
    },
    // 点击历史记录时跳转
    toSearchResult (str) {
      this.historyList = [...new Set(this.historyList)]
      this.$router.push('/search/' + str)
    }
  },
  watch: {
    historyList () {
      localStorage.setItem('history', JSON.stringify(this.historyList))
    }
  }

}
</script>

<style lang="less" scoped>
.van-field__control {
  background-color: #fff;
}
.van-search {
  height: 46px;
}
.goback {
  padding: 14px;
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
